class Solution {
public:
    bool isValidSerialization(string preorder) {
        int balance = 1;
        string cnt_str = "";
        for(int i = 0; i < preorder.size(); i++)
        {
            if(balance == 0)
                return false;
            if(preorder[i] == ',')
            {
                if(cnt_str == "#")
                    balance -= 1;
                else
                    balance += 1;
                cnt_str = "";
            }
            else
                cnt_str += preorder[i];
        }
        if(cnt_str == "#")
            balance -= 1;
        else
            balance += 1;

        return balance == 0;
    }
};